// createRouter用来创建路由对象, createWebHistory,createWebHashHistory用来指定路由模式
// 导入createRouter, createWebHistory或createWebHashHistory
import { createRouter, createWebHistory } from "vue-router";
// import { useUserStore } from "../stores/user";

// 路由数组
const routes = [
  {
    path: "/",
    component: () => import("@/view/Login.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/view/Login.vue"),
  },
  {
    path: "/home",
    component: () => import("@/view/home/index.vue"),
    meta: {
      title: "首页",
      path: "/home",
    },
  },
  {
    path: "/personal",
    name: "个人中心",
    component: () => import("@/view/personal.vue"),
    meta: {
      title: "个人中心",
      path: "/personal",
    },
  },
  {
    path: "/404",
    name: "404",
    component: () => import("@/view/404.vue"),
  },
  {
    path: "/about",
    name: "about",
  },
  {
    path: "/system",
    name: "系统管理",
    component: () => import("@/view/system/index.vue"),
    meta: {
      title: "系统管理",
      path: "/system",
    },
    children: [
      {
        path: "tenant",
        name: "租户管理",
        component: () => import("../view/system/tenant/index.vue"),
        meta: {
          title: "租户管理",
          path: "/system/tenant",
        },
        children: [
          {
            path: "list",
            name: "租户列表",
            component: () => import("../view/system/tenant/list.vue"),
            meta: {
              title: "租户列表",
              path: "/list",
            },
          },
          {
            path: "package",
            name: "租户套餐",
            component: () => import("../view/system/tenant/package.vue"),
            meta: {
              title: "租户套餐",
              path: "/package",
            },
          },
        ],
      },
      {
        path: "dept",
        name: "部门管理",
        component: () => import("@/view/system/dept/index.vue"),
        meta: {
          title: "部门管理",
          path: "/system/dept",
        },
      },
      {
        path: "menu",
        name: "菜单管理",
        component: () => import("@/view/system/menu/index.vue"),
        meta: {
          title: "菜单管理",
          path: "/system/menu",
        },
      },
      {
        path: "notice",
        name: "通知公告",
        component: () => import("../view/system/notice/index.vue"),
        meta: {
          title: "通知公告",
          path: "/system/notice",
        },
      },
    ],
  },
];

// 创建路由对象
const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 定义路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem("Authorization"); // 假设您将 token 存储在本地存储中

  if (!isAuthenticated) {
    if (to.name !== "login") {
      // 避免在登录页触发重定向
      next({ name: "login" }); // 跳转至登录页
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
